"""
网格交易策略

实现网格交易策略的核心逻辑，支持现货和合约网格
"""

import time
import math
from typing import Dict, List, Any, Optional, Tuple
from .base_strategy import BaseStrategy
from ..core.exceptions import StrategyError, ValidationError


class GridStrategy(BaseStrategy):
    """网格交易策略 - 支持现货和合约"""
    
    def __init__(self, config: Dict[str, Any], exchange_adapter, 
                 order_manager, account_manager, data_manager):
        """
        初始化网格策略
        
        Args:
            config: 策略配置
            exchange_adapter: 交易所适配器
            order_manager: 订单管理器
            account_manager: 账户管理器
            data_manager: 数据管理器
        """
        super().__init__(config, exchange_adapter, order_manager, account_manager, data_manager)
        
        # 网格策略参数
        self.grid_count = config.get('grid_count', 10)
        self.price_min = config.get('price_min', 0.0)
        self.price_max = config.get('price_max', 0.0)
        self.single_grid_amount = config.get('single_grid_amount', 100.0)
        self.stop_loss_ratio = config.get('stop_loss_ratio', 0.05)
        self.take_profit_ratio = config.get('take_profit_ratio', 0.0)  # 新增止盈比例
        self.leverage = config.get('leverage', 1)
        self.interval = config.get('interval', '5m')
        
        # 合约网格特有参数
        self.contract_type = config.get('contract_type', 'linear')  # linear/inverse
        self.position_side = config.get('position_side', 'both')    # long/short/both
        self.hedge_mode = config.get('hedge_mode', False)           # 是否对冲模式
        
        # 动态网格参数
        self.auto_adjust = config.get('auto_adjust', True)          # 是否自动调整网格
        self.adjust_threshold = config.get('adjust_threshold', 0.1)  # 调整阈值
        self.max_grid_extension = config.get('max_grid_extension', 5) # 最大扩展网格数
        
        # 风险控制参数
        self.max_position_ratio = config.get('max_position_ratio', 0.8)  # 最大仓位比例
        self.min_profit_threshold = config.get('min_profit_threshold', 0.001)  # 最小盈利阈值
        
        # 网格信息
        self.grid_levels: List[Dict[str, Any]] = []
        self.grid_orders: Dict[str, Dict[str, Any]] = {}  # order_id -> grid_info
        self.last_price = 0.0
        self.base_price = 0.0
        self.grid_profit = 0.0  # 网格总盈利
        self.grid_trades = 0    # 网格交易次数
        
        # 验证网格参数
        self._validate_grid_params()
        
        self.logger.info(f"网格策略初始化完成: {self.grid_count}个网格, 价格区间[{self.price_min}, {self.price_max}]")
        self.logger.info(f"市场类型: {self.market_type}, 合约类型: {self.contract_type}")
    
    def _validate_grid_params(self) -> None:
        """增强的网格参数验证"""
        # 基础参数验证
        if self.grid_count <= 0 or self.grid_count > 100:
            raise ValidationError("网格数量必须在1-100之间")
        
        if self.single_grid_amount <= 0:
            raise ValidationError("单网格金额必须大于0")
        
        if self.stop_loss_ratio < 0 or self.stop_loss_ratio > 1:
            raise ValidationError("止损比例必须在0-1之间")
            
        if self.take_profit_ratio < 0 or self.take_profit_ratio > 1:
            raise ValidationError("止盈比例必须在0-1之间")
        
        # 价格区间验证
        if self.price_min > 0 and self.price_max > 0:
            if self.price_min >= self.price_max:
                raise ValidationError("最低价格必须小于最高价格")
            
            price_diff_ratio = (self.price_max - self.price_min) / self.price_min
            if price_diff_ratio < 0.02:  # 最小2%的价格区间
                raise ValidationError("价格区间太小，建议至少2%")
            
            if price_diff_ratio > 2.0:   # 最大200%的价格区间
                raise ValidationError("价格区间太大，建议不超过200%")
        
        # 合约参数验证
        if self.market_type == 'futures':
            if self.leverage < 1 or self.leverage > 125:
                raise ValidationError("杠杆倍数必须在1-125之间")
            
            if self.contract_type not in ['linear', 'inverse']:
                raise ValidationError("合约类型必须是linear或inverse")
            
            if self.position_side not in ['long', 'short', 'both']:
                raise ValidationError("仓位方向必须是long、short或both")
        
        # 风险控制参数验证
        if self.max_position_ratio <= 0 or self.max_position_ratio > 1:
            raise ValidationError("最大仓位比例必须在0-1之间")
        
        if self.adjust_threshold <= 0 or self.adjust_threshold > 0.5:
            raise ValidationError("调整阈值必须在0-0.5之间")
    
    def initialize(self) -> bool:
        """初始化网格策略"""
        try:
            # 获取当前价格
            current_price = self.get_latest_price()
            if not current_price:
                self.logger.error("无法获取当前价格")
                return False
            
            self.last_price = current_price
            self.base_price = current_price
            
            # 如果没有设置价格区间，自动计算
            if self.price_min == 0.0 or self.price_max == 0.0:
                self._auto_calculate_price_range(current_price)
            
            # 验证价格区间合理性
            if not self._validate_price_range(current_price):
                return False
            
            # 生成网格
            self._generate_grid_levels()
            
            # 检查资金充足性
            if not self._check_sufficient_funds():
                return False
            
            # 放置初始网格订单
            self._place_initial_grid_orders()
            
            self.logger.info(f"网格策略初始化成功，当前价格: {current_price}")
            return True
            
        except Exception as e:
            self.logger.error(f"网格策略初始化失败: {e}")
            return False
    
    def _auto_calculate_price_range(self, current_price: float) -> None:
        """智能计算价格区间"""
        # 根据市场类型和波动率调整价格区间
        if self.market_type == 'spot':
            # 现货：相对保守的价格区间
            price_range_ratio = 0.15  # 15%
        else:
            # 合约：根据杠杆调整价格区间
            price_range_ratio = min(0.3, 0.1 + 0.02 * self.leverage)  # 最大30%
        
        price_range = current_price * price_range_ratio
        self.price_min = current_price - price_range
        self.price_max = current_price + price_range
        
        # 确保价格为正数
        self.price_min = max(self.price_min, current_price * 0.1)
        
        self.logger.info(f"自动计算价格区间: [{self.price_min:.2f}, {self.price_max:.2f}] ({price_range_ratio*100:.1f}%)")
    
    def _validate_price_range(self, current_price: float) -> bool:
        """验证价格区间合理性"""
        if current_price < self.price_min or current_price > self.price_max:
            self.logger.warning(f"当前价格 {current_price} 不在网格区间 [{self.price_min}, {self.price_max}] 内")
            
            # 自动调整价格区间
            if self.auto_adjust:
                self._auto_calculate_price_range(current_price)
                self.logger.info("已自动调整价格区间")
            else:
                return False
        
        return True
    
    def _check_sufficient_funds(self) -> bool:
        """检查资金充足性"""
        try:
            if self.market_type == 'spot':
                # 现货：检查USDT余额
                quote_currency = self.symbol.split('-')[1]
                quote_balance = self.account_manager.get_available_balance(
                    self.exchange_name, 'spot', quote_currency
                )
                
                # 计算需要的最小资金（买单总金额）
                required_funds = 0
                for level in range(self.grid_count + 1):
                    price = self.price_min + level * (self.price_max - self.price_min) / self.grid_count
                    if price < self.last_price:  # 只计算买单
                        required_funds += self.single_grid_amount
                
                if quote_balance < required_funds * 0.5:  # 至少50%的资金
                    self.logger.error(f"资金不足: 需要 {required_funds:.2f}, 可用 {quote_balance:.2f}")
                    return False
                    
            else:
                # 合约：检查保证金
                margin_balance = self.account_manager.get_available_balance(
                    self.exchange_name, 'futures', 'USDT'
                )
                
                # 计算需要的保证金
                total_position_value = self.grid_count * self.single_grid_amount
                required_margin = total_position_value / self.leverage
                
                if margin_balance < required_margin * 2:  # 至少2倍保证金
                    self.logger.error(f"保证金不足: 需要 {required_margin:.2f}, 可用 {margin_balance:.2f}")
                    return False
            
            return True
            
        except Exception as e:
            self.logger.error(f"检查资金充足性失败: {e}")
            return False
    
    def _generate_grid_levels(self) -> None:
        """生成增强的网格价格水平"""
        self.grid_levels = []
        
        # 计算网格间距
        grid_spacing = (self.price_max - self.price_min) / self.grid_count
        
        for i in range(self.grid_count + 1):
            price = self.price_min + i * grid_spacing
            
            grid_level = {
                'level': i,
                'price': price,
                'buy_order_id': None,
                'sell_order_id': None,
                'buy_filled': False,
                'sell_filled': False,
                'buy_amount': 0.0,
                'sell_amount': 0.0,
                'profit': 0.0,
                'trades': 0,
                'last_trade_time': 0,
                'is_extended': False  # 是否为扩展网格
            }
            
            self.grid_levels.append(grid_level)
        
        self.logger.info(f"生成了 {len(self.grid_levels)} 个网格价格水平，间距: {grid_spacing:.2f}")
    
    def _place_initial_grid_orders(self) -> None:
        """放置初始网格订单"""
        try:
            current_price = self.last_price
            
            for grid_level in self.grid_levels:
                grid_price = grid_level['price']
                
                # 在当前价格下方放置买单
                if grid_price < current_price:
                    self._place_grid_buy_order(grid_level)
                
                # 在当前价格上方放置卖单（如果有持仓）
                elif grid_price > current_price:
                    # 现货模式下，只有在有基础币种余额时才放置卖单
                    if self.market_type == 'spot':
                        base_currency = self.symbol.split('-')[0]
                        base_balance = self.account_manager.get_available_balance(
                            self.exchange_name, 'spot', base_currency
                        )
                        if base_balance > 0:
                            amount = min(self._calculate_grid_amount(grid_price), base_balance)
                            if amount > 0:
                                self._place_grid_sell_order(grid_level, amount)
                    else:
                        # 合约模式下可以直接放置卖单
                        self._place_grid_sell_order(grid_level)
            
            self.logger.info("初始网格订单放置完成")
            
        except Exception as e:
            self.logger.error(f"放置初始网格订单失败: {e}")
    
    def _place_grid_buy_order(self, grid_level: Dict[str, Any]) -> None:
        """放置网格买单"""
        try:
            price = grid_level['price']
            amount = self._calculate_grid_amount(price)
            
            order_id = self.place_order('limit', 'buy', amount, price, self.leverage)
            
            if order_id:
                grid_level['buy_order_id'] = order_id
                self.grid_orders[order_id] = {
                    'grid_level': grid_level['level'],
                    'type': 'buy',
                    'price': price,
                    'amount': amount
                }
                
                self.logger.debug(f"放置买单: 价格={price:.2f}, 数量={amount:.6f}")
                
        except Exception as e:
            self.logger.error(f"放置网格买单失败: {e}")
    
    def _place_grid_sell_order(self, grid_level: Dict[str, Any], amount: Optional[float] = None) -> None:
        """放置网格卖单"""
        try:
            price = grid_level['price']
            if amount is None:
                amount = self._calculate_grid_amount(price)
            
            order_id = self.place_order('limit', 'sell', amount, price, self.leverage)
            
            if order_id:
                grid_level['sell_order_id'] = order_id
                self.grid_orders[order_id] = {
                    'grid_level': grid_level['level'],
                    'type': 'sell',
                    'price': price,
                    'amount': amount
                }
                
                self.logger.debug(f"放置卖单: 价格={price:.2f}, 数量={amount:.6f}")
                
        except Exception as e:
            self.logger.error(f"放置网格卖单失败: {e}")
    
    def _calculate_grid_amount(self, price: float) -> float:
        """智能计算网格订单数量"""
        try:
            if self.market_type == 'spot':
                # 现货：根据单网格金额计算数量
                base_amount = self.single_grid_amount / price
                
                # 根据价格位置调整数量（价格越低，买入越多）
                price_ratio = price / self.base_price
                if price_ratio < 1.0:  # 价格低于基准价格
                    amount_multiplier = 1.0 + (1.0 - price_ratio) * 0.5  # 最多增加50%
                    base_amount *= amount_multiplier
                
                # 应用最小交易数量限制
                min_amount = self.exchange.get_min_trade_amount(self.symbol)
                if min_amount and base_amount < min_amount:
                    base_amount = min_amount
                
                return base_amount
            else:
                # 合约：考虑杠杆和风险
                base_amount = self.single_grid_amount / price
                
                # 根据杠杆调整数量
                leverage_factor = min(1.0, 10.0 / self.leverage)  # 杠杆越高，单笔数量越小
                base_amount *= leverage_factor
                
                # 应用最小交易数量限制
                min_amount = self.exchange.get_min_trade_amount(self.symbol)
                if min_amount and base_amount < min_amount:
                    base_amount = min_amount
                
                # 应用仓位限制
                max_position = self._get_max_position_size()
                current_position = self._get_current_position_size()
                
                if current_position + base_amount > max_position:
                    base_amount = max(0, max_position - current_position)
                
                return base_amount
                
        except Exception as e:
            self.logger.error(f"计算网格数量失败: {e}")
            return 0.0
    
    def _get_max_position_size(self) -> float:
        """获取最大仓位大小"""
        try:
            if self.market_type == 'spot':
                # 现货没有仓位限制
                return float('inf')
            
            # 合约：基于可用保证金计算最大仓位
            margin_balance = self.account_manager.get_available_balance(
                self.exchange_name, 'futures', 'USDT'
            )
            
            current_price = self.get_latest_price()
            if not current_price:
                return 0
            
            # 最大仓位 = 保证金 * 杠杆 * 仓位比例 / 价格
            max_position_value = margin_balance * self.leverage * self.max_position_ratio
            max_position_size = max_position_value / current_price
            
            return max_position_size
            
        except Exception as e:
            self.logger.error(f"获取最大仓位大小失败: {e}")
            return 0
    
    def _get_current_position_size(self) -> float:
        """获取当前仓位大小"""
        try:
            if self.market_type == 'spot':
                # 现货：返回基础币种余额
                base_currency = self.symbol.split('-')[0]
                return self.account_manager.get_available_balance(
                    self.exchange_name, 'spot', base_currency
                )
            else:
                # 合约：返回当前仓位
                position = self.account_manager.get_position(
                    self.exchange_name, 'futures', self.symbol
                )
                return abs(position.get('size', 0)) if position else 0
                
        except Exception as e:
            self.logger.error(f"获取当前仓位大小失败: {e}")
            return 0
    
    def place_order(self, order_type: str, side: str, amount: float, 
                   price: Optional[float] = None, leverage: Optional[int] = None) -> Optional[str]:
        """统一的下单接口，支持现货和合约"""
        try:
            if self.market_type == 'spot':
                # 现货下单
                return self.exchange.spot_place_order(
                    symbol=self.symbol,
                    order_type=order_type,
                    side=side,
                    amount=amount,
                    price=price
                )
            else:
                # 合约下单
                return self.exchange.futures_place_order(
                    symbol=self.symbol,
                    order_type=order_type,
                    side=side,
                    amount=amount,
                    price=price,
                    leverage=leverage or self.leverage,
                    position_side=self.position_side,
                    reduce_only=False
                )
                
        except Exception as e:
            self.logger.error(f"下单失败: {e}")
            return None
    
    def cancel_order(self, order_id: str) -> bool:
        """统一的撤单接口"""
        try:
            if self.market_type == 'spot':
                return self.exchange.spot_cancel_order(self.symbol, order_id)
            else:
                return self.exchange.futures_cancel_order(self.symbol, order_id)
        except Exception as e:
            self.logger.error(f"撤单失败: {e}")
            return False
    
    def get_latest_price(self) -> Optional[float]:
        """获取最新价格"""
        try:
            # 使用统一的get_latest_price方法
            price = self.exchange.get_latest_price(self.symbol)
            return price if price > 0 else None
        except Exception as e:
            self.logger.error(f"获取价格失败: {e}")
            return None
    
    def on_tick(self, data: Dict[str, Any]) -> None:
        """处理行情数据"""
        try:
            if not self.is_running():
                return
            
            current_price = data.get('price') or self.get_latest_price()
            if not current_price:
                return
            
            self.last_price = current_price
            self.update_last_time()
            
            # 检查止损
            if self._check_stop_loss(current_price):
                self.logger.warning("触发止损，停止策略")
                self.stop()
                return
            
            # 检查网格订单状态
            self._check_grid_orders()
            
            # 动态调整网格（如果价格超出范围）
            self._adjust_grid_if_needed(current_price)
            
        except Exception as e:
            self.logger.error(f"处理行情数据失败: {e}")
    
    def on_order_update(self, order: Dict[str, Any]) -> None:
        """处理订单更新"""
        try:
            order_id = order.get('order_id')
            status = order.get('status')
            
            if order_id not in self.grid_orders:
                return
            
            grid_info = self.grid_orders[order_id]
            grid_level_idx = grid_info['grid_level']
            grid_level = self.grid_levels[grid_level_idx]
            
            if status == 'filled':
                self._handle_grid_order_filled(order, grid_info, grid_level)
            elif status == 'cancelled':
                self._handle_grid_order_cancelled(order, grid_info, grid_level)
                
        except Exception as e:
            self.logger.error(f"处理订单更新失败: {e}")
    
    def _handle_grid_order_filled(self, order: Dict[str, Any], 
                                 grid_info: Dict[str, Any], 
                                 grid_level: Dict[str, Any]) -> None:
        """处理网格订单成交 - 增强版"""
        try:
            order_type = grid_info['type']
            filled_price = order.get('filled_price', grid_info['price'])
            filled_amount = order.get('filled_amount', grid_info['amount'])
            
            # 更新网格状态
            if order_type == 'buy':
                grid_level['buy_filled'] = True
                grid_level['buy_amount'] = filled_amount
                grid_level['buy_order_id'] = None
                
                # 计算对应的卖出价格（加上最小盈利）
                sell_price = self._calculate_sell_price(filled_price, grid_level['level'])
                
                # 放置对应的卖单
                if self.market_type == 'spot':
                    self._place_grid_sell_order(grid_level, filled_amount)
                else:
                    # 合约模式：根据仓位方向处理
                    if self.position_side in ['long', 'both']:
                        self._place_grid_sell_order(grid_level, filled_amount)
                
                self.logger.info(f"网格买单成交: 价格={filled_price:.2f}, 数量={filled_amount:.6f}")
                
            elif order_type == 'sell':
                grid_level['sell_filled'] = True
                grid_level['sell_amount'] = filled_amount
                grid_level['sell_order_id'] = None
                
                # 计算盈利
                if grid_level['buy_filled']:
                    buy_cost = grid_level['buy_amount'] * filled_price
                    sell_revenue = filled_amount * filled_price
                    profit = sell_revenue - buy_cost
                    
                    grid_level['profit'] += profit
                    self.grid_profit += profit
                    self.grid_trades += 1
                    
                    self.logger.info(f"网格交易完成: 盈利={profit:.4f}, 累计盈利={self.grid_profit:.4f}")
                
                # 重新放置买单（如果在价格区间内）
                if filled_price > self.price_min:
                    grid_level['buy_filled'] = False
                    self._place_grid_buy_order(grid_level)
                
                self.logger.info(f"网格卖单成交: 价格={filled_price:.2f}, 数量={filled_amount:.6f}")
            
            # 更新统计信息
            grid_level['trades'] += 1
            grid_level['last_trade_time'] = time.time()
            
        except Exception as e:
            self.logger.error(f"处理网格订单成交失败: {e}")
    
    def _calculate_sell_price(self, buy_price: float, grid_level: int) -> float:
        """计算卖出价格，确保最小盈利"""
        # 基础卖出价格（上一个网格价格）
        if grid_level < len(self.grid_levels) - 1:
            base_sell_price = self.grid_levels[grid_level + 1]['price']
        else:
            # 如果是最高网格，使用固定盈利比例
            base_sell_price = buy_price * (1 + self.min_profit_threshold)
        
        # 考虑交易手续费
        fee_rate = 0.001  # 假设0.1%手续费
        min_sell_price = buy_price * (1 + fee_rate * 2 + self.min_profit_threshold)
        
        return max(base_sell_price, min_sell_price)

    def _handle_grid_order_cancelled(self, order: Dict[str, Any], 
                                   grid_info: Dict[str, Any], 
                                   grid_level: Dict[str, Any]) -> None:
        """处理网格订单取消"""
        try:
            order_type = grid_info['type']
            
            if order_type == 'buy':
                grid_level['buy_order_id'] = None
            else:
                grid_level['sell_order_id'] = None
            
            # 从网格订单字典中移除
            del self.grid_orders[order['order_id']]
            
            self.logger.debug(f"网格订单已取消: {order['order_id']}")
            
        except Exception as e:
            self.logger.error(f"处理网格订单取消失败: {e}")
    
    def _check_grid_orders(self) -> None:
        """检查网格订单状态"""
        try:
            # 获取策略的所有活跃订单
            active_orders = self.order_manager.get_orders_by_strategy(self.strategy_name)
            active_orders = [order for order in active_orders 
                           if order['status'] in ['submitted', 'partial_filled']]
            
            # 检查每个网格订单的状态
            for order in active_orders:
                order_id = order['order_id']
                if order_id in self.grid_orders:
                    # 查询交易所订单状态
                    exchange_order = self.exchange.get_order_status(order_id, self.symbol)
                    if exchange_order:
                        # 更新本地订单状态
                        self.order_manager.update_order_status(
                            order_id, 
                            exchange_order['status'],
                            exchange_order.get('filled_amount'),
                            exchange_order.get('filled_price')
                        )
                        
                        # 如果订单已成交，触发订单更新处理
                        if exchange_order['status'] == 'filled':
                            self.on_order_update(exchange_order)
                            
        except Exception as e:
            self.logger.error(f"检查网格订单状态失败: {e}")
    
    def _check_stop_loss(self, current_price: float) -> bool:
        """检查是否触发止损"""
        if self.stop_loss_ratio <= 0:
            return False
        
        # 计算止损价格
        stop_loss_price = self.base_price * (1 - self.stop_loss_ratio)
        
        if current_price <= stop_loss_price:
            self.logger.warning(f"触发止损: 当前价格={current_price:.2f}, 止损价格={stop_loss_price:.2f}")
            return True
        
        return False
    
    def _adjust_grid_if_needed(self, current_price: float) -> None:
        """智能动态调整网格"""
        if not self.auto_adjust:
            return
        
        try:
            # 检查是否需要向下扩展
            if current_price < self.price_min * (1 + self.adjust_threshold):
                self._extend_grid_down(current_price)
            
            # 检查是否需要向上扩展
            elif current_price > self.price_max * (1 - self.adjust_threshold):
                self._extend_grid_up(current_price)
            
            # 检查是否需要收缩网格（移除远离价格的网格）
            self._shrink_grid_if_needed(current_price)
            
        except Exception as e:
            self.logger.error(f"动态调整网格失败: {e}")
    
    def _extend_grid_down(self, current_price: float) -> None:
        """向下扩展网格 - 增强版"""
        try:
            # 计算新的最低价格
            extension_ratio = 0.1  # 扩展10%
            new_price_min = current_price * (1 - extension_ratio)
            
            # 限制扩展次数
            extended_grids = sum(1 for level in self.grid_levels if level.get('is_extended', False))
            if extended_grids >= self.max_grid_extension:
                self.logger.warning("已达到最大网格扩展数量")
                return
            
            # 生成新的网格水平
            grid_spacing = (self.price_min - new_price_min) / 3  # 添加3个新网格
            
            for i in range(3):
                new_price = new_price_min + i * grid_spacing
                new_grid_level = {
                    'level': -i-1,  # 负数表示扩展网格
                    'price': new_price,
                    'buy_order_id': None,
                    'sell_order_id': None,
                    'buy_filled': False,
                    'sell_filled': False,
                    'buy_amount': 0.0,
                    'sell_amount': 0.0,
                    'profit': 0.0,
                    'trades': 0,
                    'last_trade_time': 0,
                    'is_extended': True
                }
                
                self.grid_levels.insert(0, new_grid_level)
                self._place_grid_buy_order(new_grid_level)
            
            self.price_min = new_price_min
            self.logger.info(f"向下扩展网格: 新最低价格={new_price_min:.2f}")
            
        except Exception as e:
            self.logger.error(f"向下扩展网格失败: {e}")
    
    def _extend_grid_up(self, current_price: float) -> None:
        """向上扩展网格 - 增强版"""
        try:
            # 计算新的最高价格
            extension_ratio = 0.1  # 扩展10%
            new_price_max = current_price * (1 + extension_ratio)
            
            # 限制扩展次数
            extended_grids = sum(1 for level in self.grid_levels if level.get('is_extended', False))
            if extended_grids >= self.max_grid_extension:
                self.logger.warning("已达到最大网格扩展数量")
                return
            
            # 生成新的网格水平
            grid_spacing = (new_price_max - self.price_max) / 3  # 添加3个新网格
            
            for i in range(3):
                new_price = self.price_max + (i + 1) * grid_spacing
                new_grid_level = {
                    'level': len(self.grid_levels) + i,  # 扩展网格
                    'price': new_price,
                    'buy_order_id': None,
                    'sell_order_id': None,
                    'buy_filled': False,
                    'sell_filled': False,
                    'buy_amount': 0.0,
                    'sell_amount': 0.0,
                    'profit': 0.0,
                    'trades': 0,
                    'last_trade_time': 0,
                    'is_extended': True
                }
                
                self.grid_levels.append(new_grid_level)
                
                # 如果有持仓，放置卖单
                if self.market_type == 'futures' or self._has_base_balance():
                    self._place_grid_sell_order(new_grid_level)
            
            self.price_max = new_price_max
            self.logger.info(f"向上扩展网格: 新最高价格={new_price_max:.2f}")
            
        except Exception as e:
            self.logger.error(f"向上扩展网格失败: {e}")
    
    def _shrink_grid_if_needed(self, current_price: float) -> None:
        """收缩远离价格的网格"""
        try:
            # 移除距离当前价格太远的扩展网格
            shrink_threshold = 0.3  # 30%
            
            grids_to_remove = []
            for i, grid_level in enumerate(self.grid_levels):
                if not grid_level.get('is_extended', False):
                    continue
                
                price_diff_ratio = abs(grid_level['price'] - current_price) / current_price
                if price_diff_ratio > shrink_threshold:
                    # 取消未成交的订单
                    if grid_level['buy_order_id']:
                        self.cancel_order(grid_level['buy_order_id'])
                    if grid_level['sell_order_id']:
                        self.cancel_order(grid_level['sell_order_id'])
                    
                    grids_to_remove.append(i)
            
            # 从后往前删除，避免索引问题
            for i in reversed(grids_to_remove):
                removed_grid = self.grid_levels.pop(i)
                self.logger.debug(f"移除远离网格: 价格={removed_grid['price']:.2f}")
            
        except Exception as e:
            self.logger.error(f"收缩网格失败: {e}")
    
    def _has_base_balance(self) -> bool:
        """检查是否有基础币种余额"""
        try:
            if self.market_type == 'spot':
                base_currency = self.symbol.split('-')[0]
                base_balance = self.account_manager.get_available_balance(
                    self.exchange_name, 'spot', base_currency
                )
                return base_balance > 0
            return True  # 合约模式总是返回True
        except:
            return False

    def get_grid_status(self) -> Dict[str, Any]:
        """获取网格状态"""
        try:
            active_buy_orders = 0
            active_sell_orders = 0
            filled_buy_orders = 0
            filled_sell_orders = 0
            
            for grid_level in self.grid_levels:
                if grid_level['buy_order_id']:
                    active_buy_orders += 1
                if grid_level['sell_order_id']:
                    active_sell_orders += 1
                if grid_level['buy_filled']:
                    filled_buy_orders += 1
                if grid_level['sell_filled']:
                    filled_sell_orders += 1
            
            return {
                'grid_count': self.grid_count,
                'price_range': [self.price_min, self.price_max],
                'current_price': self.last_price,
                'base_price': self.base_price,
                'active_buy_orders': active_buy_orders,
                'active_sell_orders': active_sell_orders,
                'filled_buy_orders': filled_buy_orders,
                'filled_sell_orders': filled_sell_orders,
                'total_grid_orders': len(self.grid_orders),
                'stop_loss_price': self.base_price * (1 - self.stop_loss_ratio) if self.stop_loss_ratio > 0 else None
            }
            
        except Exception as e:
            self.logger.error(f"获取网格状态失败: {e}")
            return {}
    
    def get_stats(self) -> Dict[str, Any]:
        """获取策略统计信息"""
        stats = super().get_stats()
        grid_status = self.get_grid_status()
        stats.update(grid_status)
        return stats

    def get_enhanced_stats(self) -> Dict[str, Any]:
        """获取增强的策略统计信息"""
        try:
            base_stats = self.get_stats()
            
            # 网格特有统计
            active_grids = sum(1 for level in self.grid_levels 
                             if level['buy_order_id'] or level['sell_order_id'])
            filled_grids = sum(1 for level in self.grid_levels 
                             if level['buy_filled'] or level['sell_filled'])
            extended_grids = sum(1 for level in self.grid_levels 
                               if level.get('is_extended', False))
            
            # 盈利分析
            profitable_grids = sum(1 for level in self.grid_levels if level['profit'] > 0)
            avg_profit_per_trade = self.grid_profit / max(self.grid_trades, 1)
            
            # 价格分析
            price_utilization = 0
            if self.last_price > 0:
                price_position = (self.last_price - self.price_min) / (self.price_max - self.price_min)
                price_utilization = min(1.0, max(0.0, price_position))
            
            enhanced_stats = {
                **base_stats,
                'grid_stats': {
                    'total_grids': len(self.grid_levels),
                    'active_grids': active_grids,
                    'filled_grids': filled_grids,
                    'extended_grids': extended_grids,
                    'grid_profit': self.grid_profit,
                    'grid_trades': self.grid_trades,
                    'profitable_grids': profitable_grids,
                    'avg_profit_per_trade': avg_profit_per_trade,
                    'price_utilization': price_utilization,
                    'price_range': {
                        'min': self.price_min,
                        'max': self.price_max,
                        'current': self.last_price,
                        'base': self.base_price
                    }
                }
            }
            
            return enhanced_stats
            
        except Exception as e:
            self.logger.error(f"获取增强统计信息失败: {e}")
            return self.get_stats()